<script setup>
import {ref} from "vue";
import {reqEmailLogin} from "@/api/modules/login.js";
import {ElMessage, ElNotification} from "element-plus";
import {loginSuccessTime} from "@/utils/time.js"
import {useRoute} from "vue-router";
import CountDown from "@/components/count-down.vue";
import {reqSendEmail4Login} from "@/api/modules/email.js";
import Verifier from "@/utils/Verifier.js";
import router from "@/router/index.js";
import {throttle} from 'lodash'
const route = useRoute()

// 验证码发送按钮状态
const isSendBtn=ref(true)

// 验证码倒计时结束
const finalCountDown=()=>{
  isSendBtn.value=true
}

const loginModel=ref({
  email:'',
  checkCode:''
})

const sendEmail= async ()=>{
  if (!isSendBtn.value){
    return
  }
  if (!loginModel.value.email){
    ElMessage.error('邮箱不能为空')
    return
  }
  await reqSendEmail4Login(loginModel.value.email)
  isSendBtn.value=false
}
const sendEmailThrottle=throttle(sendEmail,5000,{trailing:false})

const login = async () => {
    const {email,checkCode}= loginModel.value
    if (!email){
      ElMessage.error('邮箱不能为空')
      return
    }
    if (!checkCode){
      ElMessage.error('验证码不能为空')
      return
    }
    if (!Verifier.checkEmail(email)){
      ElMessage.error('邮箱格式错误')
      return
    }
    await reqEmailLogin({email,checkCode})
    ElNotification({
      title: 'Success',
      message: "欢迎回来，" + loginSuccessTime() + "好~",
      type: 'success',
      duration: 2000
    })
    await router.push("/")
}

const loginThrottle= throttle(login,5000,{trailing:false})
</script>

<template>
  <el-form :model="loginModel">
    <div class="login-title">登录页面</div>
    <el-form-item>
      <el-input placeholder="邮箱" v-model="loginModel.email">
        <template #prefix>
          <span class="iconfont icon-account"></span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <div class="check-code">
        <el-input class="input" placeholder="验证码" v-model="loginModel.checkCode"></el-input>
        <el-button type="primary" plain>
          <span v-if="isSendBtn" @click="sendEmailThrottle">发送验证码</span>
          <count-down v-else @final="finalCountDown"></count-down>
        </el-button>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button class="login-btn" type="primary" @click="loginThrottle">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.login-btn {
  width: 100%;
}


.login-title {
  font-size: 19px;
  font-weight: 700;
  text-align: center;
  margin-bottom: 10px;
  color: #ffffff;
}

.check-code {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .input {
    width: 60%;
  }

  button {
    width: 35%;
    cursor: pointer;
    height: 30px;
  }
}
</style>
